package http

import (
	"gitee.com/liukexing/mqbroker/component/model"
	"gitee.com/liukexing/mqbroker/core/driver/component"
	"gitee.com/liukexing/mqbroker/core/driver/logger"
	"gitee.com/liukexing/mqbroker/core/server/pubsub"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"time"
)

func GetTaskInfo() map[string]typedef.TaskInfo {
	TaskBootStrap()
	return map[string]typedef.TaskInfo{
		"FindRegister::@every 1m": typedef.TaskInfo{
			Name:   "注册节点查询",
			Handle: FindRegisterTask,
			Arg:    nil,
		},
		"ComReg::@every 2m": typedef.TaskInfo{
			Name:   "模块注册",
			Handle: ComRegTask,
			Arg:    nil,
		},
		"GetConfig::@every 30s": typedef.TaskInfo{
			Name:   "获取配置",
			Handle: GetConfigTask,
			Arg:    nil,
		},
		"Send::@every 1s": typedef.TaskInfo{
			Name:   "请求消息发送",
			Handle: SendTask,
			Arg:    nil,
		},
		"TimeOutCheck::@every 1s": typedef.TaskInfo{
			Name:   "请求超时检查",
			Handle: TimeOutCheckTask,
			Arg:    nil,
		},
	}
}

//初始化
func TaskBootStrap() {
	go func() {
		time.Sleep(time.Second)
		FindRegisterTask(nil)
		time.Sleep(time.Second)
		FindRegisterTask(nil)
	}()

}

//注册节点查询
func FindRegisterTask(arg map[string]interface{}) error {
	if reqid, err := component.FindRegister(Config.Info); !err {
		ReqMap.Store(reqid, typedef.MsgReceiver{Handle: "FindRegister", Stamp: time.Now(), Mutex: true, TimeOut: time.Minute})
	}
	return nil
}

//模块注册
func ComRegTask(arg map[string]interface{}) error {
	if time.Now().Sub(LastTick) > time.Minute*2 {
		FindMap.Range(func(key, value interface{}) bool {
			pubsub.CommandMsgPub(Config.Info.ID, key.(string), "Register", map[string]interface{}{"info": Config.Info})
			return false
		})
	}
	return nil
}

//获取转发模块
func GetConfigTask(arg map[string]interface{}) error {
	FindMap.Range(func(key, value interface{}) bool {
		resp := pubsub.MessageReplyClient(key.(string),"GetConfig",map[string]interface{}{"module":Config.Info.Module},20)
		if resp.Error {
			return true
		}
		c := make(map[string]interface{})
		err := typedef.Decode(resp.Data,&c)
		if err != nil {
			return  true
		}
		logger.Info(typedef.CommInfo{
			Message:c,
		})
		return false
	})
	return nil
}

//请求消息发送
func SendTask(arg map[string]interface{}) error  {
	httpcache.Range(SendMsg)
	return nil
}

//消息发送
func SendMsg(key, value interface{}) bool {
	data := value.(model.HttpWait)
	data.Send.Do(func() {
	//logger.Info(typedef.CommInfo{
	//	Message:data.Data,
	//})
	})
	return true
}

//请求超时检查
func TimeOutCheckTask(arg map[string]interface{}) error  {
	httpcache.Range(func(key, value interface{}) bool {
		data := value.(model.HttpWait)
		if data.TimeOut.Sub(time.Now()) < 0 {
			ChanReply(data,model.HttpReplyData{
				StatusCode:504,
				Content:[]byte("Request Message Timeout"),
			})
		}
		return true
	})
	return nil
}

//消息返回
func ChanReply(data model.HttpWait,reply model.HttpReplyData)  {
	data.Reply<-reply
	data.Wait.Done()
}